package com.yhb.utils;

import com.yhb.model.baidu.AddressComponent;
import com.yhb.model.baidu.PoiResp;
import lombok.extern.log4j.Log4j;
import lombok.var;
import me.edzh.spring.bootstrap.utils.JSONUtil;
import me.edzh.spring.bootstrap.utils.ResultCode;
import me.edzh.spring.bootstrap.utils.exception.ServiceException;
import me.edzh.spring.bootstrap.utils.http.ClientHolder;
import okhttp3.Request;

import java.io.IOException;

@Log4j
public class POIUtil {
    public static AddressComponent gps2Poi(String gps) {
        // 傻逼百度经度在先, 转一道

        var fuck = gps.split(",");
        if (fuck.length != 2) {
            throw new ServiceException(ResultCode.ERROR_PARAMETER_WRONG, "wrong gps format");
        }

        gps = fuck[1] + "," + fuck[0];

        Request r = new Request.Builder()
                .get()
                .url("http://api.map.baidu.com/reverse_geocoding/v3/?ak=L8FnRQy2s5LiARHNPGZafpmxEAQWHDGw&output=json&coordtype=bd09ll&language=zh-CN&location=" + gps)
                .build();

        try {
            var resp = ClientHolder.getClient().newCall(r).execute();
            var json = resp.body().string();
            log.info(json);
            var parsedResp = JSONUtil.parseJson(json, PoiResp.class);
            if (parsedResp.getStatus() != 0) {
                log.error("resolve poi failed: " + json);
                throw new RuntimeException();
            }

            return parsedResp.getResult().getAddressComponent();
        } catch (Throwable ex) {
            log.error("resolve poi failed: ", ex);
            throw new ServiceException(ResultCode.ERROR_PARAMETER_WRONG, "failed to resolve address");
        }

    }
}
